package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.basic.config.BusinessException;
import cn.itsource.org.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class GetUserInfoUtil {

    /**
     * 获取userId
     * @return
     */
    public static Long getUserId(){
        Long userId = getUserInfo().getUserId();
//        if (userId == null) {
//            throw new BusinessException("异常");
//        } else {
//            return userId;
//        }
        return Optional.ofNullable(userId).orElseThrow(()-> new BusinessException("用户id获取异常"));
    }
     /* 获取店铺id
     * @return
     */
    public static Long getShopId(){
        Long userId = getUserInfo().getShopId();
//        if (userId == null) {
//            throw new BusinessException("异常");
//        } else {
//            return userId;
//        }
        return Optional.ofNullable(userId).orElseThrow(()-> new BusinessException("店铺id获取异常"));
    }



    public static String getPhone(){
        return getUserInfo().getPhone();
    }


    public static UserInfo getUserInfo(){
        //1.从请求头里面获取token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //2.从redis拿到token的值
        String token = request.getHeader("token");

        //3.通过hutool从spring的ioc容器获取到RedisService这个对象
        RedisService redisService = SpringUtil.getBean(RedisService.class);

        //4.获取userInfo对象
        UserInfo userInfo = redisService.getKeyObjectValue(token, UserInfo.class);

        return userInfo;
    }


}
